package com.hxzy.system.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.constant.UserConstants;
import com.hxzy.common.core.domain.TreeSelect;
import com.hxzy.common.core.domain.entity.SysDept;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.utils.StringUtils;
import com.hxzy.common.utils.spring.SpringUtils;
import com.hxzy.system.mapper.SysDeptMapper;
import com.hxzy.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {


    @Override
    public List<SysDept> selectDeptList (SysDept dept) {
        return this.baseMapper.selectDeptList(dept);
    }

    @Override
    public String checkDeptNameUnique (SysDept sysDept) {
        Long id = StringUtils.isNull(sysDept.getParentId()) ? - 1 : sysDept.getParentId();
        SysDept dept = this.baseMapper.checkDeptNameUnique(sysDept.getDeptName(), sysDept.getParentId());
        if (StringUtils.isNotNull(dept) && dept.getDeptId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int inserDept (SysDept sysDept) {
        SysDept dept = this.baseMapper.selectDeptById(sysDept.getParentId());
        if (! UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            throw new ServiceException("部门停用,不允许新增");
        }
        sysDept.setAncestors(dept.getAncestors() + "," + sysDept.getParentId());
        sysDept.setCreateTime(new Date());
        return this.baseMapper.insertDept(sysDept);
    }

    @Override
    public SysDept selectDeptById (Long id) {
        return this.baseMapper.selectDeptById(id);
    }

    @Override
    public int updateDept (SysDept sysDept) {
        // 当前部门信息
        SysDept dept = this.baseMapper.selectDeptById(sysDept.getDeptId());
        // 获取父级部门信息
        SysDept oldDept = this.baseMapper.selectDeptById(sysDept.getParentId());
        if (StringUtils.isNotNull(oldDept)&& StringUtils.isNotNull(dept)) {
            // 拼接 祖级列表
            String newAncestors = oldDept.getAncestors() + "," + oldDept.getDeptId();
            // 当前部门的祖级列表
            String oldAncestors = dept.getAncestors();
            sysDept.setAncestors(newAncestors);
            this.updateDeptChildren(sysDept.getDeptId(),newAncestors,oldAncestors);
        }
        int result = this.baseMapper.updateDept(sysDept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(sysDept);
        }
        return result;
    }

    @Override
    public boolean hasChildByDeptId (Long deptId) {
        int i = this.baseMapper.hasChildByDeptId(deptId);
        return i > 0;
    }

    @Override
    public boolean checkDeptExistUser (Long deptId) {
        int i = this.baseMapper.checkDeptExistUser(deptId);
        return i > 0;
    }

    @Override
    public int deleteDeptById (Long deptId) {
        return this.baseMapper.deleteDeptById(deptId);
    }



    /**
     * 构建前端所需要下拉树结构
     *
     * @param sysDepts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysDept> sysDepts) {
        List<SysDept> deptTrees = buildMenuTree(sysDepts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }


    /**
     * 构建前端所需要树结构
     *
     * @param sysDepts 部门列表
     * @return 树结构列表
     */
    private List<SysDept> buildMenuTree(List<SysDept> sysDepts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : sysDepts) {
            tempList.add(dept.getDeptId());
        }
        for (SysDept sysDept : sysDepts) {
            // 如果是顶级节点, 遍历该父节点的所
            // 子节点
            if (!tempList.contains(sysDept.getParentId())) {
                recursionFn(sysDepts, sysDept);
                returnList.add(sysDept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = sysDepts;
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */

    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0;
    }

    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 修改部门正常状态
     * @param dept
     */
    private void updateParentDeptStatusNormal (SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        this.baseMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子节点的祖级列表
     * @param deptId
     * @param newAncestors
     * @param oldAncestors
     */
    private void updateDeptChildren (Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> sysDepts = this.baseMapper.selectChildrenDeptById(deptId);

        for (SysDept child : sysDepts)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (sysDepts.size() > 0)
        {
            this.baseMapper.updateDeptChildren(sysDepts);
        }
    }
}
